/**
 * file
 */
package com.tdkj.action.front.member;

import java.io.FileInputStream;
import java.io.IOException;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Properties;
import java.util.Random;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.struts2.ServletActionContext;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSenderImpl;

import com.opensymphony.xwork2.Action;
import com.opensymphony.xwork2.ActionContext;
import com.tdkj.action.BaseAction;
import com.tdkj.model.enterprisezone.BeanEnterprise;
import com.tdkj.model.enterprisezone.BeanEnterpriseZone;
import com.tdkj.model.financial.BeanFinancialAccount;
import com.tdkj.model.shop.BeanGoodShowcase;
import com.tdkj.model.shop.BeanShelf;
import com.tdkj.model.shop.BeanShop;
import com.tdkj.model.shop.BeanShoppingCart;
import com.tdkj.model.user.BeanUser;
import com.tdkj.model.user.BeanUserLevel;
import com.tdkj.model.user.BeanUserLoginLog;
import com.tdkj.model.user.BeanUserPersonal;
import com.tdkj.model.user.BeanValidateEmil;
import com.tdkj.service.user.IBeanUserLoginLogService;
import com.tdkj.service.user.IBeanUserService;
import com.tdkj.util.PublicConfing;
import com.tdkj.util.md5.MD5Util;

import freemarker.template.Configuration;

/**
 * 
 * FileName: MemberAction.java
 * 
 * @Description: 会员中心
 * 
 *               All rights Reserved, Designed By ZTE-ITS
 * 
 *               Copyright: Copyright(C) 2010-2011
 * 
 *               Company 天成科技有限公司
 * 
 * @author: 李兴建
 * 
 * @version V1.0
 * 
 *          Createdate: 2012-5-16 下午09:34:07
 * 
 * 
 * 
 *          Modification History:
 * 
 *          Date Author Version Discription
 * 
 * 
 * 
 * 
 * 
 * 
 * 
 * 
 * 
 * 
 * 
 * 
 * 
 * 
 * 
 * 
 * 
 * 
 * 
 * 
 * 
 * 
 * 
 * 
 * 
 * 
 * 
 * 
 * 
 * 
 * 
 * 
 * 
 * 
 * 
 * 
 * 
 * 
 *          
 *          ----------------------------------------------------------------------
 *          -------------
 * 
 *          2012-5-16 李兴建 1.0 1.0
 * 
 *          Why & What is modified: <修改原因描述>
 */
public class MemberAction extends BaseAction {

	private static final long serialVersionUID = -5294859509883233849L;
	private IBeanUserService userService;
	private BeanUser beanUser;
	private BeanUserPersonal personal;
	private BeanEnterprise enterprise;
	private BeanEnterpriseZone enterpriseZone;
	private BeanShop beanShop;
	private String authcode;
	private String registerRule;
	private String reuserpassword;
	private String validateRandom;

	private IBeanUserLoginLogService userLoginLogService;

	private JavaMailSenderImpl mailSender;
	private SimpleMailMessage mailMessage;

	private String registerinfo;

	private boolean isValidate;

	private String reEmail;

	/**
	 * 跳转登录页面
	 * 
	 * @return
	 */
	public String loginPage() throws Exception {
		/*
		 * BeanUser beanUser=new BeanUser(); beanUser.setUserLoginName("admin");
		 * beanUser.setUserpassword("admin");
		 * 
		 * BeanUserPersonal beanUserPersonal=new BeanUserPersonal();
		 * beanUserPersonal.setEmail("867424981@qq.com");
		 * beanUser.setPersonal(beanUserPersonal); //beanUser.set
		 * sendEmail(beanUser);
		 */
		beanUser = new BeanUser();
		validateRandom = "";
		return "loginPage";
	}
	/**
	 * 到个人中心
	 * 
	 * @return
	 */
	public String toMemberCenter() throws Exception {
		return "loginSuccess";
	}

	/**
	 * 退出
	 * 
	 * @return
	 */
	public String lognOut() {
		ActionContext.getContext().getSession().put(
				PublicConfing.MEMBER_MEMBWE_OBJ_STRING_CONFIG, null);
		BeanUserLoginLog userLoginLog = null;
		if (null != ActionContext.getContext()
				&& null != ActionContext.getContext().getSession()
				&& null != ActionContext.getContext().getSession().get(
						PublicConfing.MEMBER_LOGIN_LOG))
			userLoginLog = (BeanUserLoginLog) ActionContext.getContext()
					.getSession().get(PublicConfing.MEMBER_LOGIN_LOG);
		if (null != userLoginLog)
			userLoginLogService.createLogoutLog(userLoginLog.getId());
		ActionContext.getContext().getSession().put(
				PublicConfing.MEMBER_LOGIN_LOG, null);
		ActionContext.getContext().getSession().put(
				PublicConfing.MEMBER_LAST_LOGIN_LOG, null);
		return "lognOut";
	}

	/**
	 * 登录
	 * 
	 * @return
	 */
	public String login() {

		// 用户名格式不正确
		if (StringUtils.isEmpty(beanUser.getUserLoginName())) {
			this.addFieldError("beanUser.userLoginName", "用户名不能为空");
			return "loginPage";
		}
		// 密码格式不正确
		if (StringUtils.isEmpty(beanUser.getUserpassword())) {
			this.addFieldError("beanUser.userpassword", "密码格式不正确");
			return "loginPage";
		}

		List<BeanUser> objList = userService.findByProperty("userLoginName",
				beanUser.getUserLoginName(), BeanUser.class);
		// 登录失败没有找到用户
		if (null == objList || objList.size() < 1) {
			this.addFieldError("beanUser.userLoginName", "用户名不正确");
			return "loginPage";
		}
		BeanUser user = objList.get(0);
		// 登录失败，密码不正确
		if (!user.getUserpassword().equals(
				MD5Util.md5Encrypt(beanUser.getUserpassword()))) {
			this.addFieldError("beanUser.userpassword", "密码不正确");
			return "loginPage";
		}
		// 登录失败，验证码不正确
		String cv = (String) ActionContext.getContext().getSession().get(
				PublicConfing.MEMBER_LOGIN_RANDOM);
		if ("".equals(validateRandom) || !validateRandom.equals(cv)) {
			this.addFieldError("validateRandom", "验证码不正确,请重新输入");
			return "loginPage";
		}

		user = userService.getUser(user.getId());
		// 登录成功

		if (!user.isVerificationEmail()) {
			isValidate = true;
			this.addFieldError("beanUser.userLoginName", "你的邮箱尚未验证，请你登录邮箱进行验证");
			return "loginPage";
		}

		ActionContext.getContext().getSession().put(
				PublicConfing.MEMBER_LOGIN_STATA_LOGIN, "login");
		ActionContext.getContext().getSession().put(
				PublicConfing.MEMBER_MEMBWE_OBJ_STRING_CONFIG, user);

		HttpServletRequest request = (HttpServletRequest) ActionContext
				.getContext().get(ServletActionContext.HTTP_REQUEST);

		BeanUserLoginLog lastUserLoginLog = userLoginLogService
				.getLastLoginLog(user.getId());
		ActionContext.getContext().getSession().put(
				PublicConfing.MEMBER_LAST_LOGIN_LOG, lastUserLoginLog);

		BeanUserLoginLog userLoginLog = userLoginLogService.createLoginLog(user
				.getId(), request.getRemoteAddr());
		ActionContext.getContext().getSession().put(
				PublicConfing.MEMBER_LOGIN_LOG, userLoginLog);

		// 重定向
		if (null != ActionContext.getContext().getSession().get(
				PublicConfing.MEMBER_REDIRECTURL_TEMP)) {
			String url = (String) ActionContext.getContext().getSession().get(
					PublicConfing.MEMBER_REDIRECTURL_TEMP);
			// System.out.println("登录得到地址：" + url);
			HttpServletResponse response = ServletActionContext.getResponse();
			try {
				ActionContext.getContext().getSession().put(
						PublicConfing.MEMBER_REDIRECTURL_TEMP, null);
				response.sendRedirect(url);
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			return null;
		}
		// this.getSession().setAttribute(PublicConfing.MEMBER_MEMBWE_OBJ_STRING_CONFIG,
		// usre);
		return "loginSuccess";
	}

	/**
	 * 找回密码
	 * 
	 * @return
	 * @throws Exception 
	 */
	public String findPwd() throws Exception {

		// 邮箱格式不正确
		if (StringUtils.isEmpty(reEmail)) {
			this.addFieldError("reEmailErroe", "邮箱不能为空");
			return findPasswordPage();
		}
		// 邮箱格式不正确
		Pattern p1 = Pattern
				.compile("^([a-z0-9A-Z]+[-|\\.]?)+[a-z0-9A-Z]@([a-z0-9A-Z]+(-[a-z0-9A-Z]+)?\\.)+[a-zA-Z]{2,}$");
		Matcher m = p1.matcher(reEmail);
		if (!m.matches()) {
			this.addFieldError("reEmailErroe", "邮箱格式不正确");
			return findPasswordPage();
		}
		//do
		BeanUserPersonal bp=null;
		bp=(BeanUserPersonal) this.getBaseService().findByProperty("email", reEmail, BeanUserPersonal.class);
		
		if(null==bp){
			this.addFieldError("reEmailErroe", "邮箱格式不正确");
			return findPasswordPage();
		}
		sendEmailByToker(reEmail);
		this.addFieldError("reEmailErroe", "请在您的邮箱内查收密码！");
		
		
		return Action.SUCCESS;
	}

	/*
	 * @Override public void validate() { if(null==this.beanUser){ return ; }
	 * if(null == this.beanUser.getUsername() ||
	 * "".equals(this.beanUser.getUsername().trim())) {
	 * //第一个参数表示表单中的textfield的name,第二参数是提示信息
	 * this.addFieldError("beanUser.username", "UserName is required!"); }
	 * 
	 * }
	 */
	/**
	 * 找回密码页面
	 * 
	 */
	public String findPasswordPage() {
		return "findPasswordPage";
	}
	/**
	 * 重置密码页面
	 * @return
	 */
	public String editPasswordPage(){
		return "editPasswordPage";
	}
	/**
	 * 跳转注册页面
	 * 
	 * @return
	 */
	public String registerPage() throws Exception {
		if (beanUser == null) {
			personal = new BeanUserPersonal();
			beanUser = new BeanUser();
		}
		return "registerPage";
	}

	public String enterpriseRegisterPage() throws Exception {
		if (beanUser == null) {
			beanUser = new BeanUser();
			enterprise = new BeanEnterprise();
			enterpriseZone = new BeanEnterpriseZone();
			beanShop = new BeanShop();
		}
		return "enterpriseRegisterPage";
	}
	public String editPwd(){
		
		// 密码格式不正确
		if (StringUtils.isEmpty(beanUser.getUserpassword())) {
			this.addFieldError("beanUser.userpassword", "密码格式不正确");
			return editPasswordPage();
		}
		// 密码格式不正确
		if (beanUser.getUserpassword().length() < 6) {
			this.addFieldError("beanUser.userpassword", "密码长度不够");
			return editPasswordPage();
		}
		// 密码格式不正确
		if (StringUtils.isEmpty(this.getReuserpassword())) {
			this.addFieldError("reuserpassword", "密码格式不正确");
			return editPasswordPage();
		}
		// 密码格式不正确
		if (!this.getReuserpassword().equals(beanUser.getUserpassword())) {
			this.addFieldError("reuserpassword", "两次密码输入不正确");
			return editPasswordPage();
		}
		
		return editPasswordPage();
	}
	/**
	 * 发送令牌邮件
	 * 
	 * @param user
	 * @return
	 */
	public String sendEmailByToker(String email) throws Exception {
		BeanValidateEmil beanValidateEmil = new BeanValidateEmil();
		/*
		 * beanValidateEmil.setEmail(user.getPersonal().getEmail());
		 * beanValidateEmil
		 * .setUserName(MD5Util.md5Encrypt(user.getUserLoginName()));
		 * beanValidateEmil
		 * .setPassword(MD5Util.md5Encrypt(user.getUserpassword()));
		 */
		beanValidateEmil.setRandomStr(getRandomString(100));
		beanValidateEmil
				.setSenderTime(new Timestamp(System.currentTimeMillis()));
		// beanValidateEmil.setEmail(user.getPersonal().getEmail());

		StringBuffer projectRealPath = ServletActionContext.getRequest()
				.getRequestURL();
		StringBuffer re = new StringBuffer(projectRealPath.substring(0,
				projectRealPath.lastIndexOf("/")).toString());
		// http://localhost:8080/xnky/memberCenter
		re.append("/validateEmailAction.action?randomStr="
				+ beanValidateEmil.getRandomStr());

		Properties prop = new Properties();// 属性集合对象
		String filePath = Configuration.class.getResource("/").getPath()
				+ "WebSiteConfig.properties";
		if (filePath.contains("%20")) {
			filePath = filePath.replaceAll("%20", " ");
		}
		if (filePath.startsWith("/")) {
			filePath = filePath.replaceFirst("/", "");
		}
		FileInputStream fis = new FileInputStream(filePath);// 属性文件输入流
		prop.load(fis);// 将属性文件流装载到Properties对象中

		// String subject;
		String host;
		String addr;
		String name;
		String pwd;

		// subject = prop.getProperty("Email_Config_subject");
		host = prop.getProperty("Email_Config_host");
		addr = prop.getProperty("Email_Config_addr");
		name = prop.getProperty("Email_Config_name");
		pwd = prop.getProperty("Email_Config_password");

		SimpleMailMessage msg = new SimpleMailMessage(mailMessage);
		// msg.setSubject("西南矿业网");
		msg.setFrom(addr);

		mailSender.setHost(host);
		mailSender.setUsername(name);
		mailSender.setPassword(pwd);

		msg.setTo(email);
		StringBuffer str = new StringBuffer();
		str.append("重置密码，请点击下面链接进入密码重置页面!!\n");
		str.append(re.toString());
		str.append("\n\n【西南矿业网】");
		msg.setText(str.toString());
		mailSender.send(msg);
		this.getBaseService().save(beanValidateEmil);
		this.setRegisterinfo("注册成功，请登录你的注册邮箱进行验证,登录并在个人中心完善你的个人或企业信息 ");
		return editPasswordPage();

	}
	@SuppressWarnings("unchecked")
	public String personalRegister() throws Exception {
		Boolean isRegisterSuccess = true;
		/*
		 * // 用户名格式不正确 if (StringUtils.isEmpty(beanUser.getUsername())) {
		 * this.addFieldError("beanUser.username", "用户名不能为空"); isRegisterSuccess
		 * = false; } // 用户名格式不正确 if (beanUser.getUsername().length() < 4) {
		 * this.addFieldError("beanUser.username", "用户名长度不够"); isRegisterSuccess
		 * = false; } List<BeanUser> list =
		 * userService.findByProperty("username", beanUser.getUsername(),
		 * BeanUser.class); // 已经有账号注册 if (list.size() > 0) {
		 * this.addFieldError("beanUser.username", "该用户名已经注册");
		 * isRegisterSuccess = false; }
		 */

		// 登录名格式不正确
		if (StringUtils.isEmpty(beanUser.getUserLoginName())) {
			this.addFieldError("beanUser.userLoginName", "登录名不能为空");
			isRegisterSuccess = false;
		}
		// 登录名格式不正确
		if (beanUser.getUserLoginName().length() < 4) {
			this.addFieldError("beanUser.userLoginName", "登录名长度不够");
			isRegisterSuccess = false;
		}
		// 已经有登录名账号注册
		if (userService.findByProperty("userLoginName",
				beanUser.getUserLoginName(), BeanUser.class).size() > 0) {
			this.addFieldError("beanUser.userLoginName", "该登录名已经注册");
			isRegisterSuccess = false;
		}

		// 密码格式不正确
		if (StringUtils.isEmpty(beanUser.getUserpassword())) {
			this.addFieldError("beanUser.userpassword", "密码格式不正确");
			isRegisterSuccess = false;
		}
		// 密码格式不正确
		if (beanUser.getUserpassword().length() < 6) {
			this.addFieldError("beanUser.userpassword", "密码长度不够");
			isRegisterSuccess = false;
		}
		// 密码格式不正确
		if (StringUtils.isEmpty(this.getReuserpassword())) {
			this.addFieldError("reuserpassword", "密码格式不正确");
			isRegisterSuccess = false;
		}
		// 密码格式不正确
		if (!this.getReuserpassword().equals(beanUser.getUserpassword())) {
			// beanUser.setUserpassword("");
			// this.setReuserpassword("");
			this.addFieldError("reuserpassword", "两次密码输入不正确");
			isRegisterSuccess = false;
		}
		/*
		 * // 密码找回问题不正确 if (StringUtils.isEmpty(beanUser.getPwdquestion())) {
		 * this.addFieldError("beanUser.pwdquestion", "密码找回问题格式不正确");
		 * isRegisterSuccess = false; } // 密码找回答案不正确 if
		 * (StringUtils.isEmpty(beanUser.getPwdanswer())) {
		 * this.addFieldError("beanUser.pwdanswer", "密码找回答案格式不正确");
		 * isRegisterSuccess = false; }
		 */
		// 邮箱不能空
		if (StringUtils.isEmpty(personal.getEmail())) {
			this.addFieldError("personal.email", "邮箱不能空");
			isRegisterSuccess = false;
		}
		// 邮箱格式不正确
		Pattern p1 = Pattern
				.compile("^([a-z0-9A-Z]+[-|\\.]?)+[a-z0-9A-Z]@([a-z0-9A-Z]+(-[a-z0-9A-Z]+)?\\.)+[a-zA-Z]{2,}$");
		Matcher m = p1.matcher(personal.getEmail());
		if (!m.matches()) {
			this.addFieldError("personal.email", "邮箱格式不正确");
			isRegisterSuccess = false;
		}
		// 检测邮箱是否注册过
		List<BeanUser> list2 = this.createQuery(
				"from " + BeanUser.class.getName()
						+ " as bean where bean.personal.email = '"
						+ personal.getEmail() + "'").list();
		if (list2.size() > 0) {
			this.addFieldError("personal.email", "该邮箱已注册");
			isRegisterSuccess = false;
		}
		/*
		 * //检测邮箱的真实性
		 * if(CheckEmailWS.checkEmail(beanUser.getPersonal().getEmail())){
		 * this.addFieldError("beanUser.personal.email", "邮箱地址不真实");
		 * isRegisterSuccess = false; }
		 */

		// 验证码不正确
		String cv = (String) ActionContext.getContext().getSession().get(
				PublicConfing.MEMBER_LOGIN_RANDOM);
		if ("".equals(validateRandom) || !validateRandom.equals(cv)) {
			this.addFieldError("validateRandom", "验证码不正确,请重新输入");
			isRegisterSuccess = false;
		}

		if (!isRegisterSuccess) {
			return "registerPage";
		}
		System.out.print(authcode);
		BeanUserLevel level = new BeanUserLevel();
		level.setId(1L);
		userService.save(level);

		beanUser.setUserLevel(level);

		BeanFinancialAccount beanAccount = new BeanFinancialAccount();
		/*
		 * beanAccount.setGoldMoney(0L); beanAccount.setIntegralCount(0L);
		 * beanAccount.setMineCurrencyMoney(0L);
		 */
		this.getBaseService().save(beanAccount);
		beanUser.setFinancialAccount(beanAccount);

		// 购物车
		BeanShoppingCart shoppingCart = new BeanShoppingCart();
		beanUser.setShoppingCart(shoppingCart);

		// 个人基本信息
		personal.setSex("男");
		personal.setAge(0);
		personal.setQq("");
		personal.setSignature("我的地盘我做言主");
		personal.setRealName("");
		personal.setBirthday(new Date());
		personal.setMobilephone("");
		personal.setAddress("");
		personal.setProvince("");
		personal.setCity("");
		personal.setZipCode("");
		personal.setIdNumber("");
		personal.setImgUrl("images/user_ico_image.png");
		this.getBaseService().save(personal);
		beanUser.setPersonal(personal);

		// md5加密
		String md5str = MD5Util.md5Encrypt(beanUser.getUserpassword());
		beanUser.setUserpassword(md5str);
		beanUser.setRegistDateTime(new Timestamp(System.currentTimeMillis()));
		beanUser.setRegistIP(ServletActionContext.getRequest().getRemoteAddr());
		BeanUserLevel bean = this.getBaseService().findByProperty("levelname",
				"普通会员", BeanUserLevel.class).get(0);
		beanUser.setUserLevel(bean);
		beanUser.setVerificationEmail(false);
		beanUser.setExperience(0);
		userService.save(beanUser);
		insetBBSUser(beanUser);

		// ActionContext.getContext().getSession().put(PublicConfing.MEMBER_LOGIN_STATA_LOGIN,
		// "login");
		// ActionContext.getContext().getSession().put(PublicConfing.MEMBER_MEMBWE_OBJ_STRING_CONFIG,
		// beanUser);
		sendEmail(beanUser);
		return "registerSuccess";
	}

	@SuppressWarnings("unchecked")
	public String enterpriseRegister() throws Exception {
		Boolean isRegisterSuccess = true;
		/*
		 * // 用户名格式不正确 if (StringUtils.isEmpty(beanUser.getUsername())) {
		 * this.addFieldError("beanUser.username", "用户名不能为空"); isRegisterSuccess
		 * = false; } // 用户名格式不正确 if (beanUser.getUsername().length() < 3) {
		 * this.addFieldError("beanUser.username", "用户名长度不够"); isRegisterSuccess
		 * = false; } List<BeanUser> list =
		 * userService.findByProperty("username", beanUser.getUsername(),
		 * BeanUser.class); // 已经有账号注册 if (list.size() > 0) {
		 * this.addFieldError("beanUser.username", "该用户名已经注册");
		 * isRegisterSuccess = false; }
		 */
		// 用户名格式不正确
		if (StringUtils.isEmpty(beanUser.getUserLoginName())) {
			this.addFieldError("beanUseruserLoginNameErrorVlidate", "用户名格式不正确");
			isRegisterSuccess = false;
		}

		// 密码格式不正确
		if (StringUtils.isEmpty(beanUser.getUserpassword())) {
			this.addFieldError("beanUseruserpasswordErrorVlidate", "密码格式不正确");
			isRegisterSuccess = false;
		}
		// 密码格式不正确
		if (beanUser.getUserpassword().length() < 6) {
			this.addFieldError("beanUseruserpasswordErrorVlidate", "密码长度不够");
			isRegisterSuccess = false;
		}
		// 密码格式不正确
		if (StringUtils.isEmpty(this.getReuserpassword())) {
			this.addFieldError("reuserpasswordErrorVlidate", "密码格式不正确");
			isRegisterSuccess = false;
		}
		// 密码格式不正确
		if (!this.getReuserpassword().equals(beanUser.getUserpassword())) {
			// beanUser.setUserpassword("");
			// this.setReuserpassword("");
			this.addFieldError("reuserpasswordErrorVlidate", "两次密码输入不正确");
			isRegisterSuccess = false;
		}

		if (StringUtils.isEmpty(enterprise.getName())) {
			this.addFieldError("enterprisenameErrorVlidate", "公司名称格式不正确");
			isRegisterSuccess = false;
		}
		if (StringUtils.isEmpty(enterprise.getAddress())) {
			this.addFieldError("enterpriseaddressErrorVlidate", "公司地址格式不正确");
			isRegisterSuccess = false;
		}
		if (StringUtils.isEmpty(enterprise.getBusinessScope())) {
			this.addFieldError("enterprisebusinessScopeErrorVlidate",
					"主营项目格式不正确");
			isRegisterSuccess = false;
		}
		if (StringUtils.isEmpty(enterpriseZone.getName())) {
			this.addFieldError("enterpriseZonenameErrorVlidate", "空间名称格式不正确");
			isRegisterSuccess = false;
		}
		if (StringUtils.isEmpty(beanShop.getName())) {
			this.addFieldError("beanShopnameErrorVlidate", "店铺名称格式不正确");
			isRegisterSuccess = false;
		}

		/*
		 * // 密码找回问题不正确 if (StringUtils.isEmpty(beanUser.getPwdquestion())) {
		 * this.addFieldError("beanUser.pwdquestion", "密码找回问题格式不正确");
		 * isRegisterSuccess = false; } // 密码找回答案不正确 if
		 * (StringUtils.isEmpty(beanUser.getPwdanswer())) {
		 * this.addFieldError("beanUser.pwdanswer", "密码找回答案格式不正确");
		 * isRegisterSuccess = false; }
		 */
		// 邮箱不能空
		if (StringUtils.isEmpty(personal.getEmail())) {
			this.addFieldError("personalemailErrorVlidate", "邮箱不能空");
			isRegisterSuccess = false;
		}
		// 邮箱格式不正确
		Pattern p1 = Pattern
				.compile("^([a-z0-9A-Z]+[-|\\.]?)+[a-z0-9A-Z]@([a-z0-9A-Z]+(-[a-z0-9A-Z]+)?\\.)+[a-zA-Z]{2,}$");
		Matcher m = p1.matcher(personal.getEmail());
		if (!m.matches()) {
			this.addFieldError("personalemailErrorVlidate", "邮箱格式不正确");
			isRegisterSuccess = false;
		}
		// 检测邮箱是否注册过
		List<BeanUser> list2 = this.createQuery(
				"from " + BeanUser.class.getName()
						+ " as bean where bean.personal.email = '"
						+ personal.getEmail() + "'").list();
		if (list2.size() > 0) {
			this.addFieldError("personalemailErrorVlidate", "该邮箱已注册");
			isRegisterSuccess = false;
		}

		// 登录失败，验证码不正确
		String cv = (String) ActionContext.getContext().getSession().get(
				PublicConfing.MEMBER_LOGIN_RANDOM);
		if ("".equals(validateRandom) || !validateRandom.equals(cv)) {
			this.addFieldError("validateRandom", "验证码不正确,请重新输入");
			return "enterpriseRegisterPage";
		}

		if (!isRegisterSuccess) {
			return "enterpriseRegisterPage";
		}
		System.out.print(authcode);
		BeanUserLevel level = new BeanUserLevel();
		level.setId(1L);
		userService.save(level);

		beanUser.setUserLevel(level);
		// 将企业加入
		beanUser.setEnterprise(enterprise);
		// 将空间加入
		beanUser.setEnterpriseZone(enterpriseZone);

		// 信用
		beanUser.setCreditScore(0);

		// ----------------------店铺 start--------------------------->
		beanShop.setCreateDate(new Date(System.currentTimeMillis()));
		beanShop.setShowcase(new BeanGoodShowcase());
		List<BeanShelf> shelfs = new ArrayList<BeanShelf>();
		shelfs.add(new BeanShelf());
		beanShop.setShelfs(shelfs);
		beanUser.setShop(beanShop);

		// ----------------------店铺 end--------------------------->

		// 购物车
		BeanShoppingCart shoppingCart = new BeanShoppingCart();
		beanUser.setShoppingCart(shoppingCart);

		BeanFinancialAccount beanAccount = new BeanFinancialAccount();
		/*
		 * beanAccount.setGoldMoney(0L); beanAccount.setIntegralCount(0L);
		 * beanAccount.setMineCurrencyMoney(0L);
		 */
		this.getBaseService().save(beanAccount);
		beanUser.setFinancialAccount(beanAccount);

		// md5加密
		String md5str = MD5Util.md5Encrypt(beanUser.getUserpassword());
		beanUser.setUserpassword(md5str);

		// 个人基本信息
		personal.setSex("男");
		personal.setAge(0);
		personal.setQq("");
		personal.setSignature("我的地盘我做言主");
		personal.setRealName("");
		personal.setBirthday(new Date());
		personal.setMobilephone("");
		personal.setAddress("");
		personal.setProvince("");
		personal.setCity("");
		personal.setZipCode("");
		personal.setIdNumber("");
		personal.setImgUrl("images/conpany_ico_image.png");

		this.getBaseService().save(personal);
		beanUser.setPersonal(personal);
		// 企业
		beanUser.setAccountType(1);
		beanUser.setVerificationEmail(false);
		beanUser.setExperience(0);
		userService.save(beanUser);
		insetBBSUser(beanUser);

		// ActionContext.getContext().getSession().put(PublicConfing.MEMBER_LOGIN_STATA_LOGIN,
		// "login");
		// ActionContext.getContext().getSession().put(PublicConfing.MEMBER_MEMBWE_OBJ_STRING_CONFIG,
		// beanUser);
		sendEmail(beanUser);
		return "registerSuccess";
	}

	public BeanUser getBeanUser() {
		return beanUser;
	}

	public void setBeanUser(BeanUser beanUser) {
		this.beanUser = beanUser;
	}

	public String getAuthcode() {
		return authcode;
	}

	public void setAuthcode(String authcode) {
		this.authcode = authcode;
	}

	public String getRegisterRule() {
		return registerRule;
	}

	public void setRegisterRule(String registerRule) {
		this.registerRule = registerRule;
	}

	public String getReuserpassword() {
		return reuserpassword;
	}

	public void setReuserpassword(String reuserpassword) {
		this.reuserpassword = reuserpassword;
	}

	public IBeanUserService getUserService() {
		return userService;
	}

	@Resource
	public void setUserService(IBeanUserService userService) {
		this.userService = userService;
	}

	public String getValidateRandom() {
		return validateRandom;
	}

	public void setValidateRandom(String validateRandom) {
		this.validateRandom = validateRandom;
	}

	public BeanEnterprise getEnterprise() {
		return enterprise;
	}

	public void setEnterprise(BeanEnterprise enterprise) {
		this.enterprise = enterprise;
	}

	public BeanEnterpriseZone getEnterpriseZone() {
		return enterpriseZone;
	}

	public void setEnterpriseZone(BeanEnterpriseZone enterpriseZone) {
		this.enterpriseZone = enterpriseZone;
	}

	public void insetBBSUser(BeanUser user) {
		/*
		 * SimpleDateFormat dateFormat = new
		 * SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); String dateTime =
		 * dateFormat.format(new Date(System.currentTimeMillis())); String sex =
		 * "U"; String ip = ServletActionContext.getRequest().getRemoteAddr();
		 * if (user.getPersonal().getSex().equals("男")) { sex = "M"; } else if
		 * (user.getPersonal().getSex().equals("女")) { sex = "F"; } String sql =
		 * "INSERT INTO `ejf_user` VALUES ('" + user.getUserLoginName() + "','"
		 * + user.getUsername() + "','" +
		 * BBSMD5.MD5(BBSMD5.MD5(user.getUserpassword())) + "','" +
		 * user.getPersonal().getEmail() + "','" + user.getPersonal().getQq() +
		 * "','" + sex + "',NULL,'U','1970-01-01',NULL,'" + ip +
		 * "',NULL,'F',0,0,0,'1','" + dateTime + "',1,0,NULL,NULL,'N','" +
		 * dateTime + "','" + dateTime + "')";
		 * this.getBaseService().getBaseDao()
		 * .getSession().createSQLQuery(sql).executeUpdate();
		 */}

	public void setMailMessage(SimpleMailMessage mailMessage) {
		this.mailMessage = mailMessage;
	}

	public void setMailSender(JavaMailSenderImpl mailSender) {
		this.mailSender = mailSender;
	}

	/**
	 * 发送验证邮件
	 * 
	 * @param user
	 * @return
	 */
	public String sendEmail(BeanUser user) throws Exception {
		BeanValidateEmil beanValidateEmil = new BeanValidateEmil();
		/*
		 * beanValidateEmil.setEmail(user.getPersonal().getEmail());
		 * beanValidateEmil
		 * .setUserName(MD5Util.md5Encrypt(user.getUserLoginName()));
		 * beanValidateEmil
		 * .setPassword(MD5Util.md5Encrypt(user.getUserpassword()));
		 */
		beanValidateEmil.setRandomStr(getRandomString(100));
		beanValidateEmil
				.setSenderTime(new Timestamp(System.currentTimeMillis()));
		// beanValidateEmil.setEmail(user.getPersonal().getEmail());
		beanValidateEmil.setUser(user);

		StringBuffer projectRealPath = ServletActionContext.getRequest()
				.getRequestURL();
		StringBuffer re = new StringBuffer(projectRealPath.substring(0,
				projectRealPath.lastIndexOf("/")).toString());
		// http://localhost:8080/xnky/memberCenter
		re.append("/validateEmailAction.action?randomStr="
				+ beanValidateEmil.getRandomStr());

		Properties prop = new Properties();// 属性集合对象
		String filePath = Configuration.class.getResource("/").getPath()
				+ "WebSiteConfig.properties";
		if (filePath.contains("%20")) {
			filePath = filePath.replaceAll("%20", " ");
		}
		if (filePath.startsWith("/")) {
			filePath = filePath.replaceFirst("/", "");
		}
		FileInputStream fis = new FileInputStream(filePath);// 属性文件输入流
		prop.load(fis);// 将属性文件流装载到Properties对象中

		// String subject;
		String host;
		String addr;
		String name;
		String pwd;

		// subject = prop.getProperty("Email_Config_subject");
		host = prop.getProperty("Email_Config_host");
		addr = prop.getProperty("Email_Config_addr");
		name = prop.getProperty("Email_Config_name");
		pwd = prop.getProperty("Email_Config_password");

		SimpleMailMessage msg = new SimpleMailMessage(mailMessage);
		// msg.setSubject("西南矿业网");
		msg.setFrom(addr);

		mailSender.setHost(host);
		mailSender.setUsername(name);
		mailSender.setPassword(pwd);

		msg.setTo(user.getPersonal().getEmail());
		StringBuffer str = new StringBuffer();
		str.append("注册成功，请你点击下面的链接激活你的账号\n");
		str.append(re.toString());
		str.append("\n\n【西南矿业网】");
		msg.setText(str.toString());
		mailSender.send(msg);
		this.getBaseService().save(beanValidateEmil);
		this.setRegisterinfo("注册成功，请登录你的注册邮箱进行验证,登录并在个人中心完善你的个人或企业信息 ");
		return Action.SUCCESS;

	}

	/**
	 * 产生一个随机的字符串
	 * 
	 * @param 字符串长度
	 * @return
	 */
	public static String getRandomString(int length) {
		Random random = new Random();
		StringBuffer sb = new StringBuffer();
		for (int i = 0; i < length; i++) {
			int number = random.nextInt(3);
			long result = 0;
			switch (number) {
			case 0:
				result = Math.round(Math.random() * 25 + 65);
				sb.append(String.valueOf((char) result));
				break;
			case 1:
				result = Math.round(Math.random() * 25 + 97);
				sb.append(String.valueOf((char) result));
				break;
			case 2:
				sb.append(String.valueOf(new Random().nextInt(10)));
				break;
			}
		}
		return sb.toString();
	}

	public static void main(String[] args) {
		System.out.println(getRandomString(50));
	}

	@Resource
	public void setUserLoginLogService(
			IBeanUserLoginLogService userLoginLogService) {
		this.userLoginLogService = userLoginLogService;
	}

	/**
	 * @return the registerinfo
	 */
	public String getRegisterinfo() {
		return registerinfo;
	}

	/**
	 * @param registerinfo
	 *            the registerinfo to set
	 */
	public void setRegisterinfo(String registerinfo) {
		this.registerinfo = registerinfo;
	}

	/**
	 * @return the isValidate
	 */
	public boolean getIsValidate() {
		return isValidate;
	}

	/**
	 * @param isValidate
	 *            the isValidate to set
	 */
	public void setValidate(boolean isValidate) {
		this.isValidate = isValidate;
	}

	/**
	 * @return the personal
	 */
	public BeanUserPersonal getPersonal() {
		return personal;
	}

	/**
	 * @param personal
	 *            the personal to set
	 */
	public void setPersonal(BeanUserPersonal personal) {
		this.personal = personal;
	}

	/**
	 * @return the beanShop
	 */
	public BeanShop getBeanShop() {
		return beanShop;
	}

	/**
	 * @param beanShop
	 *            the beanShop to set
	 */
	public void setBeanShop(BeanShop beanShop) {
		this.beanShop = beanShop;
	}

	public String getReEmail() {
		return reEmail;
	}

	public void setReEmail(String reEmail) {
		this.reEmail = reEmail;
	}

}
